﻿using System;
using System.IO;

namespace ParsePtb.Comm
{
    public class LogsHelper
    {

        public static string rootPath = AppDomain.CurrentDomain.BaseDirectory;

        /// <summary>
        ///  日志打印
        /// </summary>
        /// <param name="message"></param>
        public static void addLog(string str, string name = "管理员", string writeFileName = "parseLog.txt")
        {
            InsertLog(str, name, writeFileName);
        }

        /// <summary>
        ///  错误日志打印
        /// </summary>
        /// <param name="message"></param>
        public static void AddErrorLog(string str, string name = "管理员", string writeFileName = "errorLogs.txt")
        {
            InsertLog(str, name, writeFileName);
        }



        /// <summary>
        ///  日志插入信息
        /// </summary>
        /// <param name="message"></param>
        public static void InsertLog(string str, string name, string writeFileName)
        {
            //获取当前日期
            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string path = rootPath + writeFileName;
            FileStream fs = null;
            StreamWriter sw = null;
            try
            {
                if (!File.Exists(path))
                {
                    fs = new FileStream(path, FileMode.Create, FileAccess.Write);
                    sw = new StreamWriter(fs);
                    long fl = fs.Length;
                    fs.Seek(fl, SeekOrigin.End);
                    sw.WriteLine("时间 :" + time + "   操作员姓名:" + name + "        操作:" + str + "\n");//开始写入值
                }
                else
                {
                    fs = new FileStream(path, FileMode.Open, FileAccess.Write);
                    sw = new StreamWriter(fs);
                    long fl = fs.Length;
                    fs.Seek(fl, SeekOrigin.Begin);
                    sw.WriteLine("时间 :" + time + "   操作员姓名:" + name + "        操作:" + str + "\n");//开始写入值
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"日志输入异常:{ex.Message}");
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }



    }
}
